/*
 * @Description: 条目检测 - 真实性检测
 * @Author: Rfan
 * @Date: 2022-10-10 14:19:09
 * @LastEditTime: 2022-10-22 11:58:51
 */

import { forwardRef, Key, Ref, useEffect, useImperativeHandle, useState } from 'react';
import { Table, Tabs, Typography } from 'antd';
import classnames from 'classnames/bind';
import { jsonClone } from '@/utils';
import { editItemById, insertItem, selectItemByKey } from '@/utils/list';
import { useAddPlanDialogContext } from '../../../../contexts/AddPlanDialogContext';
import {
  CheckProps,
  EnumAuthenticityRuleType,
  EnumCheckContentType
} from '../../../../../../../dictionaries';
import FieldLength from './components/FieldLength';
import FieldType from './components/FieldType';
import FieldFormat from './components/FieldFormat';
import FieldRange from './components/FieldRange';
import Repeatability from './components/Repeatability';
import SpecialChar from './components/SpecialChar';
import type { ILevel } from '@/interfaces/archiveType';
import type { IPropsRuleWithSetting } from '../../../../../../../interface';
import styles from '../../../../styles/entryPanes.module.scss';
import mainStyles from '../../../../styles/main.module.scss';

const cx = classnames.bind(styles);
const mainCx = classnames.bind(mainStyles);

const { TabPane } = Tabs;
const { Column } = Table;

const authenticityInitRules = [
  {
    ruleType: 1,
    ruleValid: false,
    rule: {
      contentType: EnumCheckContentType.Regular,
      content: ''
    }
  },
  {
    ruleType: 2,
    ruleValid: false,
    rule: {
      contentType: EnumCheckContentType.Regular,
      content: 0
    }
  }
];

// 字段规则各层级字段规则类型
export interface IAuthenticationFieldLevelRule {
  key?: Key;
  field: string;
  rules: IPropsRuleWithSetting<EnumAuthenticityRuleType>[];
}

// 真实性字段规则类型
export interface IAuthenticationFieldRules {
  level: number;
  levelName: string;
  rules: IAuthenticationFieldLevelRule[];
}

// 条目真实性完整类型
export interface IAuthenticationPart {
  ruleType: number;
  rules: IAuthenticationFieldRules[];
}

// 条目真实性完整类型
export interface IAuthenticationFullRules {
  ruleType: CheckProps.Authenticity;
  rules: IAuthenticationPart[];
}

const EntryAuthentication = forwardRef((props: any, ref: Ref<unknown>) => {
  const { levelFieldList, combineLeveAndRulesInfo } = useAddPlanDialogContext();

  // 当前选中的tab
  const [currentTab, setCurrentTab] = useState<string>('');
  // 表格内容
  const [initTable, setInitTable] = useState<IAuthenticationFieldLevelRule[]>([]);
  // excel列与元数据字段关系
  const [colRelation, setColRelation] = useState<IAuthenticationFieldRules[]>([]);

  useImperativeHandle(ref, () => ({
    save: () => {
      const levelRules: IAuthenticationFieldRules[] = saveTableForm();
      const fullRules: IAuthenticationFullRules = {
        ruleType: CheckProps.Authenticity,
        rules: [
          {
            ruleType: 1,
            rules: levelRules
          }
        ]
      };
      return fullRules;
    }
  }));

  useEffect(() => {
    if (levelFieldList.length > 0) {
      setCurrentTab(levelFieldList[0].level + '');
    }
  }, [levelFieldList]);

  useEffect(() => {
    if (currentTab && levelFieldList.length > 0) {
      const numCurTab = parseInt(currentTab, 10);
      const currentData: IAuthenticationFieldRules = colRelation.find(
        (item: any) => item.level === numCurTab
      );
      setInitTable(
        currentData?.rules ||
          combineLeveAndRulesInfo(
            CheckProps.Authenticity,
            numCurTab,
            jsonClone(authenticityInitRules)
          )
      );
    }
  }, [currentTab, levelFieldList]);

  /**
   * @description: tab切换
   * @param {string} key 选中的tab的key
   */
  const tabsChange = (key: string) => {
    saveTableForm();
    setCurrentTab(key);
  };

  /**
   * @description: 保存当前层级填入字段
   */
  const saveTableForm = () => {
    const newState: IAuthenticationFieldRules[] = jsonClone(colRelation);
    const currentLevel: ILevel =
      selectItemByKey(parseInt(currentTab, 10), levelFieldList, 'level') || {};
    const { level, levelName } = currentLevel;

    if (newState.length > 0) {
      let flag: boolean = false;
      newState.forEach((item) => {
        if (item.level === level) {
          item.rules = initTable;
          flag = true;
        }
      });
      // 如果循环完没有当前层级
      if (!flag) {
        newState.push({
          level,
          levelName,
          rules: initTable
        });
      }
    } else {
      newState.push({
        level,
        levelName,
        rules: initTable
      });
    }
    setColRelation(newState);
    return newState;
  };

  /**
   * @description: 保存单元格操作选择的内容
   * @param {Key} key 条目key
   * @param {number} type 检测类型
   * @param {any} data 修改后的检测规则
   */
  const saveRules = (key: Key, type: number, data: any) => {
    // 修改的条目
    const selectData = selectItemByKey(key, initTable, 'key');
    const rules = selectItemByKey(type, selectData?.rules || [], 'ruleType')
      ? editItemById(type, data, selectData.rules, 'ruleType')
      : insertItem(data, selectData.rules);
    setInitTable((state) => editItemById(key, { ...selectData, rules }, state, 'key'));
  };

  const operations = {
    left: (
      <Typography.Text className={cx('auth-tab-title')} strong>
        元数据设置
      </Typography.Text>
    )
  };

  return (
    <>
      <div className={mainCx('property-wrap')}>
        <Tabs activeKey={currentTab} tabBarExtraContent={operations} onChange={tabsChange}>
          {levelFieldList.map((level: ILevel) => (
            <TabPane tab={level.levelName} key={level.level}>
              <Table dataSource={initTable} size="small" pagination={false} bordered>
                <Column title="元数据项" dataIndex="field" key="field" align="center" />
                <Column
                  title="长度"
                  dataIndex="length"
                  key="length"
                  align="center"
                  render={(_val, record: any) => <FieldLength data={record} onChange={saveRules} />}
                />
                <Column
                  title="类型"
                  dataIndex="type"
                  key="type"
                  align="center"
                  render={(_val, record: any) => <FieldType data={record} onChange={saveRules} />}
                />
                <Column
                  title="格式"
                  dataIndex="name"
                  key="name"
                  align="center"
                  render={(_val, record: any) => <FieldFormat data={record} onChange={saveRules} />}
                />
                <Column
                  title="值域"
                  dataIndex="name"
                  key="name"
                  align="center"
                  render={(_val, record: any) => <FieldRange data={record} onChange={saveRules} />}
                />
                <Column
                  title="重复性"
                  dataIndex="name"
                  key="name"
                  align="center"
                  render={(_val, record: any) => (
                    <Repeatability data={record} onChange={saveRules} />
                  )}
                />
                <Column
                  title="特殊字符检测"
                  dataIndex="name"
                  key="name"
                  align="center"
                  render={(_val, record: any) => <SpecialChar data={record} onChange={saveRules} />}
                />
              </Table>
            </TabPane>
          ))}
        </Tabs>
      </div>
      {/* 编制规则 */}
      {/* <div className={cs(mainCx('property-wrap'), cx('metadata-rule'))}> */}
      {/*  <Space className={cx('metadata-rule--space')} direction="vertical"> */}
      {/*    <Row> */}
      {/*      <Col span={4}> */}
      {/*        <Checkbox>档号编制规则</Checkbox> */}
      {/*      </Col> */}
      {/*      <Col> */}
      {/*        <Button type="text">设置规则</Button> */}
      {/*      </Col> */}
      {/*    </Row> */}
      {/*    <Row> */}
      {/*      <Col span={7}> */}
      {/*        <Checkbox>元数据是否关联内容数据检测</Checkbox> */}
      {/*      </Col> */}
      {/*      <Col> */}
      {/*        <Button type="text">设置规则</Button> */}
      {/*      </Col> */}
      {/*    </Row> */}
      {/*  </Space> */}
      {/* </div> */}
    </>
  );
});

export default EntryAuthentication;
